<?php

namespace common\models;

use Yii;

class Youdao{

    public static function getText($word){
        $text = file_get_contents("http://dict.youdao.com/w/".$word."/#keyfrom=dict2.top");
        return $text;
    }

    /**
     * 得到单词
     * @param $text
     */
    public static function getWord($text){
        $pattern = "/\<h2\s+class=\"wordbook-js\"\>\s+\<span\s+class=\"keyword\"\>([\s\S]*?)<\/span\>/";
        preg_match_all($pattern, $text, $matchs);
        //echo '<pre>';print_r($matchs);
        $word = isset($matchs[1][0]) ? $matchs[1][0] : "";
        return $word;
    }

    /**
     * 得到音标
     * @param $word
     * @return array
     */
    public static function getIPA($text){

        //echo $text;
        $pattern = "/\<div\s+class=\"baav\"\>([\s\S]*?)\<\/div\>/";
        preg_match_all($pattern, $text, $matchs);
        //echo '<pre>';print_r($matchs);exit;
        $ipaText = isset($matchs[1][0]) ? $matchs[1][0] : "";
        preg_match_all("/\<span\s+class=\"phonetic\"\>(.*?)\<\/span\>/", $ipaText, $matchs_ipa);
        //echo '<pre>';print_r($matchs_ipa);exit;
        $ipas = isset($matchs_ipa[1]) ? $matchs_ipa[1] : [];
        return $ipas;
    }

    public static function getChineseTrans($text){

        $pattern = "/\<div\s+class=\"trans-container\">\s+\<ul\>([\s\S]*?)\<\/ul\>/";
        preg_match_all($pattern, $text, $matchs);
        //echo '<pre>';print_r($matchs);exit;
        $trantsText = isset($matchs[1][0]) ? $matchs[1][0] : "";
//        echo $trantsText;

        preg_match_all("/\<li\>(.*?)\<\/li\>/", $trantsText, $matchs_tran);
        //echo '<pre>';print_r($matchs);exit;

        $trans = isset($matchs_tran[1]) ? $matchs_tran[1] : [];
        return $trans;

    }

    /**
     * 得到提取内容
     * @param $text
     * @return array
     */
    public static function getInfo($word){
        $text = self::getText($word);
        $data = [];
        $data["word"] = self::getWord($text);
        $data["ipa"] = self::getIPA($text);
        $data["trans"] = self::getChineseTrans($text);
        return $data;
    }

}
